package com.example.commen.base;

import static com.example.commen.utile.StatusBarUtil.initbar;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.commen.utile.NetworkBroadcastReceiver;
import com.blankj.utilcode.util.LogUtils;
import com.example.commen.aop.SingleClick;
import com.example.commen.base.dialoglib.CommonInterface;
import com.example.commen.bean.EventBusEntity;
import com.example.commen.interf.IBaseActivity;
import com.example.commen.resource.CommentContect;
import com.example.commen.view.WaitDialog;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.hjq.gson.factory.GsonFactory;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.toast.Toaster;
import com.tencent.bugly.crashreport.CrashReport;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;

import okhttp3.Call;


public class BaseActivity extends AppCompatActivity implements IBaseActivity,TitleBarAction, OnHttpListener<Object> {
    private WaitDialog.Builder dialog;
    private CommonInterface.OnPermissionCallBack listeren;
    private Parcelable mIntentData;
    private TitleBar mTitleBar;
    private View.OnClickListener titleRightClickListener;
    private View.OnClickListener titleLeftClickListener;
    private View.OnClickListener titleTextViewClickListener;

    //------------------------------------------------------
    public Parcelable getIntentData() {
        return mIntentData;
    }

    public ActivityResultLauncher<Intent> mLauncherBase = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    LogUtils.i("onActivityResult ", GsonFactory.getSingletonGson().toJson(result));
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        onActivityResults(result);
                    }
                }
            }
    );
    /**
     * startactivity 返回
     *
     * @param result
     */
    public void onActivityResults(ActivityResult result) {
    }

    private boolean isHid = true;
    NetworkBroadcastReceiver myReceiver = new NetworkBroadcastReceiver();
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        setRequestedOrientation(ActivityInfo
//                .SCREEN_ORIENTATION_LANDSCAPE);// 横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        if (isHid) {
            initbar(this);
        }
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if (getIntent() != null && getIntent().getExtras() != null) {
            mIntentData = getIntent().getParcelableExtra(CommentContect.intentKey.Data);
            //java.lang.ClassCastException: java.lang.String cannot be cast to android.os.Parcelable
        }
        initObserve();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

        // 动态注册广播接收器
        registerReceiver(myReceiver, intentFilter);
    }

    /**
     * onCreate调用
     */
    public void initObserve() {
    }

    /**
     * 是否设置标题栏透明
     *
     * @param isHid true:设置为透明
     */
    public void setIsHidStateBar(boolean isHid) {
        this.isHid = isHid;
    }

    @Override
    protected void onStart() {
        super.onStart();
        try {
            initData();
            initListener();
        } catch (Exception e) {
            ShowToast(e.toString());
            e.printStackTrace();
        }
    }

    /**
     * 防止 官方 onBackPressed 的废弃而
     */
    public void onBackPressed() {
        getOnBackPressedDispatcher().onBackPressed();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventMainThread(EventBusEntity event) {
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        LogUtils.d("`````````当前内存级别:" + level);
        if (TRIM_MEMORY_UI_HIDDEN == level) {
//            System.gc();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
    @Override
    protected void onDestroy() {
        unregisterReceiver(myReceiver);
        //注销消息接收
        if (dialog != null) {
            dialog.dismiss();
        }
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 1&&grantResults.length!=0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.i("Meet10","5");
                if (listeren != null) {
                    listeren.onPermissionGranted();
                }
            } else {
                Log.i("Meet10","6");
                if (listeren != null) {
                    listeren.onPermissionDenied();
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public void showProgress(String message) {
        if (dialog == null || !dialog.isShowing()) {
            dialog = new WaitDialog.Builder(this);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setCancelable(true);
//        new ProgressDialog(this, message);
            dialog.show();
        }
    }
    public void showProgressOk(String message) {
        if (dialog == null || !dialog.isShowing()) {
//            dialog = new ProgressDialog(this, message,false,true);
            dialog = new WaitDialog.Builder(this);
            dialog.setCanceledOnTouchOutside(true);
            dialog.setCancelable(true);
            dialog.show();
        }
    }
    public void dismissProgress() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }
    public void ShowToast(String string){
        Toaster.show(string);
        LogUtils.i("Toaster:"+string);
    }
    /**
     * 设置标题栏的标题
     */
    @Override
    public void setTitle(@StringRes int id) {
        setTitle(getString(id));
    }


    /**
     * 设置标题栏的标题
     */
    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);
        if (getTitleBar() != null) {
            getTitleBar().setLeftTitle(title);
        }
    }




    @Override
    public void onLeftClick(View view) {
        onBackPressed();
    }
    private ViewGroup getlayoutView() {
        return (ViewGroup) getContentView();
    }
    @Override
    @Nullable
    public TitleBar getTitleBar() {
//        if (mTitleBar == null) {
        mTitleBar = obtainTitleBar(getlayoutView());
        if (mTitleBar!=null)
        mTitleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            @SingleClick
            public void onLeftClick(View view) {
                if (titleLeftClickListener!=null) {
                    titleLeftClickListener.onClick(view);
                }else{
                   onBackPressed();
                }

            }

            @Override
            @SingleClick
            public void onTitleClick(View view) {
                if (titleTextViewClickListener!=null)
                    titleTextViewClickListener.onClick(view);
            }

            @Override
            @SingleClick
            public void onRightClick(View view) {
                if (titleRightClickListener!=null)
                    titleRightClickListener.onClick(view);
            }
        });
//        }
        return mTitleBar;
    }

    public TitleBar setTitleRightClickListener(View.OnClickListener onClickListener){
        titleRightClickListener = onClickListener;
        return mTitleBar;
    }
    public TitleBar setTitleLeftClickListener(View.OnClickListener onClickListener){
        titleLeftClickListener = onClickListener;
        return mTitleBar;
    }
    public TitleBar setTitleTextViewClickListener(View.OnClickListener onClickListener){
        titleTextViewClickListener = onClickListener;
        return mTitleBar;
    }

    public void requestPermission(String permission, CommonInterface.OnPermissionCallBack callBack) {
        this.listeren = callBack;
        if (Build.VERSION.SDK_INT >= 23) {
            /**
             *   该方法是检查是否具有此权限:
             *      PackageManager.PERMISSION_DENIED：该权限是被拒绝的。
             *      PackageManager.PERMISSION_GRANTED：该权限是被授权的。
             */
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                Log.i("Meet10","1");
                //没有授权权限
                /**
                 * shouldShowRequestPermissionRationale：
                 *      判断以后是否拒绝且选择不再提示,因为如果用户拒绝且不再提示的话,此处就会没有任何反应
                 */
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                    Log.i("Meet10","2");
                    if (listeren != null) {
                        listeren.onPrompt();
                    }
                } else {
                    Log.i("Meet10","3");
                    ActivityCompat.requestPermissions(this, new String[]{permission}, 1);
                }
            } else {
                Log.i("Meet10","4");
                //授权了,直接执行
                if (listeren != null) {
                    listeren.onPermissionGranted();
                }
            }
        } else {
            //6.0一下,只要在Manifest里面申明就具有权限。即使被三方限制了也没法提供api获取,只能提供try...catch完成
            if (listeren != null) {
                listeren.onPermissionGranted();
            }
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus()) {
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    public void goToActivity(Context context, Class toActivity) {
        Intent intent = new Intent(context, toActivity);
        startActivity(intent);
        overridePendingTransition(0, 0);
    }

    public void goToActivityForResult(Context context, Class toActivity, Object data) {
        Intent intent = new Intent(context, toActivity);
        intent.putExtra(CommentContect.intentKey.Data, (Serializable) data);
        mLauncherBase.launch(intent);
    }

    public void goToActivityForResult(Context context, Class toActivity, int result) {
        Intent intent = new Intent(context, toActivity);
        startActivityForResult(intent, result);
    }

    public void goToActivityForResult(Context context, Class toActivity, String data, int result) {
        Intent intent = new Intent(context, toActivity);
        intent.putExtra(CommentContect.intentKey.Data, data);
        startActivityForResult(intent, result);
    }

    public void goToActivity(Context context, Class toActivity, String data) {
        Intent intent = new Intent(context, toActivity);
        intent.putExtra(CommentContect.intentKey.Data,data);
        startActivity(intent);
        overridePendingTransition(0, 0);
    }
    public void goToActivity(Context context, Class toActivity, Long data) {
        Intent intent = new Intent(context, toActivity);
        intent.putExtra(CommentContect.intentKey.Data,data);
        startActivity(intent);
        overridePendingTransition(0, 0);
    }
    public void goToActivity(Context context, Class toActivity, Object data) {
        Intent intent = new Intent(context, toActivity);
        intent.putExtra(CommentContect.intentKey.Data,(Serializable) data);
        startActivity(intent);
        overridePendingTransition(0, 0);
    }
    public void goToActivity(Context context, Class toActivity, Parcelable data) {
        Intent intent = new Intent(context, toActivity);
        intent.putExtra(CommentContect.intentKey.Data, data);
        startActivity(intent);
        overridePendingTransition(0, 0);
    }
    public void goToActivity(Context context, Class toActivity,String key, String data) {
        Intent intent = new Intent(context, toActivity);
        intent.putExtra(key,data);
        startActivity(intent);
        overridePendingTransition(0, 0);
    }
    public void goToActivity(Context context, Class toActivity,String key, boolean data) {
        Intent intent = new Intent(context, toActivity);
        intent.putExtra(key, data);
        startActivity(intent);
        overridePendingTransition(0, 0);
    }

    public void goToActivity(Context context, Class toActivity, Bundle data) {
        Intent intent = new Intent(context, toActivity);
        intent.putExtra(CommentContect.intentKey.Bundle, data);
        startActivity(intent);
        overridePendingTransition(0, 0);
    }

    /**
     * onStart调用
     */
    @Override
    public void initListener() {

    }

    /**
     * onStart调用
     */
    @Override
    public void initData() {

    }

    /**
     * 和 setContentView 对应的方法
     */
    public ViewGroup getContentView() {
        return findViewById(Window.ID_ANDROID_CONTENT);
    }

    private ArrayList<Long> progressDialogMap = new ArrayList<>();

    @Override
    public void onStart(Call call) {
        if (progressDialogMap.isEmpty()) {
            showProgress("拉取数据中...");
        }
        progressDialogMap.add(System.currentTimeMillis());
    }

    @Override
    public void onSucceed(Object result) {

    }

    @Override
    public void onFail(Exception e) {
        CrashReport.postCatchedException(e);
    }

    @Override
    public void onEnd(Call call) {
        if (!progressDialogMap.isEmpty()){
            progressDialogMap.remove(0);
        }
        if (progressDialogMap.isEmpty()) {
            dismissProgress();
        }
    }
}
